package com.xiyou.weblog.web.service.Impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiyou.weblog.common.domain.dos.ArticleDO;
import com.xiyou.weblog.common.domain.mapper.ArticleMapper;
import com.xiyou.weblog.common.utils.PageResponse;
import com.xiyou.weblog.common.utils.Response;
import com.xiyou.weblog.web.model.vo.archive.FindArchiveArticlePageListReqVO;
import com.xiyou.weblog.web.model.vo.archive.FindArchiveArticlePageListRspVO;
import com.xiyou.weblog.web.model.vo.archive.FindArchiveArticleRspVO;
import com.xiyou.weblog.web.service.ArchiveService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xiyou
 * @description 文章归档模块
 */

@Service
@Slf4j
public class ArchiveServiceImpl implements ArchiveService {

    @Resource
    private ArticleMapper articleMapper;

    /**
     * 获取文章归档分页数据
     */
    @Override
    public Response findArchivePageList(FindArchiveArticlePageListReqVO findArchiveArticlePageListReqVO) {
        Long current = findArchiveArticlePageListReqVO.getCurrent();
        Long size = findArchiveArticlePageListReqVO.getSize();

        //分页查询
        Page<ArticleDO> page = articleMapper.selectPageList(null, current, size, null, null);
        List<ArticleDO> articleDOS = page.getRecords();

        List<FindArchiveArticlePageListRspVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(articleDOS)) {
            List<FindArchiveArticleRspVO> articleRspVOS = articleDOS.stream().map(articleDO ->
                    FindArchiveArticleRspVO.builder()
                            .id(articleDO.getId())
                            .title(articleDO.getTitle())
                            .cover(articleDO.getCover())
                            .createMonth(YearMonth.from(articleDO.getCreateTime()))
                            .createDate(articleDO.getCreateTime().toLocalDate())
                            .build())
                    .toList();

            // 按创建的月份进行分组
            Map<YearMonth, List<FindArchiveArticleRspVO>> map = articleRspVOS.stream().collect(Collectors.groupingBy(FindArchiveArticleRspVO::getCreateMonth));
            // 使用 TreeMap 按月份倒序排列
            TreeMap<YearMonth,List<FindArchiveArticleRspVO>> sortedMap = new TreeMap<>(Collections.reverseOrder());
            sortedMap.putAll(map);

            // 遍历排序后的 Map，将其转换为归档 VO
            sortedMap.forEach((yearMonth, list) -> vos.add(FindArchiveArticlePageListRspVO.builder().month(yearMonth).articles(list).build()));
        }
        return PageResponse.success(page, vos);
    }
}
